package com.freesky.biz.activity.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.freesky.common.core.controller.BaseController;
import com.freesky.common.core.domain.AjaxResult;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/weixin/webhook")
public class WebhookController extends BaseController {

    private static final String WEB_HOOK_URL = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=23315a40-d096-4758-b766-c2cecc661e5d";
    //https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=23315a40-d096-4758-b766-c2cecc661e5d
    //http://127.0.0.1:8080/weixin/webhook/pushToWechat
    //https://pay.weixin.qq.com/index.php/core/info
    @PostMapping("/pushToWechat")
    public AjaxResult pushToWechat(@Validated @RequestBody String content) {
        System.out.println("content:"+content);
        String BASE64_IMAGE = "data:image/png;base64,";
        JSONObject jsonObject = JSON.parseObject(content);
        String base64 = jsonObject.getString("base64");
        base64 = base64.replaceAll(BASE64_IMAGE,"");
        System.out.println("base64:"+base64);
        //byte[] decodeBase64 = Base64.decodeBase64(base64);
        String sign = DigestUtils.md5Hex(Base64.decodeBase64(base64));
        //SecureUtil.md5(new String(Base64.decodeBase64(base64)));
        System.out.println("sign:"+sign);
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("msgtype","image");
        Map<String,Object> imageMap = new HashMap<>();
        imageMap.put("base64",base64);
        imageMap.put("md5",sign);
        paramMap.put("image",imageMap);

        FileUtil.writeBytes(Base64.decodeBase64(base64),new File("/Users/zhengxiansheng/Documents/test.png"));
        String result = HttpRequest.post(WEB_HOOK_URL)
                .header(Header.USER_AGENT, "Chrome")
                .header(Header.CONTENT_TYPE,"application/json")
                .charset("utf8")
                .body(JSON.toJSONString(paramMap))
                .timeout(10000)
                .execute().body();
        System.out.println(result);

        return AjaxResult.success();
    }

}
